package com.wuyunonline.tracelog.interceptor;

import com.wuyunonline.tracelog.common.constant.TraceLogConstant;
import com.wuyunonline.tracelog.common.util.TraceIdUtil;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * springMVC traceId拦截器
 * @author wuyun
 */
public class TraceLogWebMvcInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String method = request.getMethod();
        // 放行跨域预请求
        if (method.equals("OPTIONS")) {
            return true;
        }
        String traceId = request.getHeader(TraceLogConstant.TRACE_ID);
        if (StringUtils.isEmpty(traceId)) {
            traceId = TraceIdUtil.uuid_timestamp();
        }
        MDC.put(TraceLogConstant.TRACE_ID, traceId);
        return true;
    }
}
